from fastapi import FastAPI, Request, HTTPException
from app.routers import test, log, users, auth  # 导入我们创建的路由
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from app.exceptions import AuthException
from app.middlewares.custom_middleware import CustomMiddleware

app = FastAPI()

# 注册全局中间件（正确方式）
@app.middleware("http")
async def global_middleware_wrapper(request: Request, call_next):
    return await CustomMiddleware.global_middleware(request, call_next)

# 处理认证异常
@app.exception_handler(AuthException)
async def auth_exception_handler(request: Request, exc: AuthException):
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "code": exc.detail.get("code", 401),
            "msg": exc.detail.get("msg", "认证失败"),
            "data": None
        }
    )

# 处理其他HTTP异常（可选）
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "code": exc.status_code,
            "msg": exc.detail,
            "data": None
        }
    )

# 注册test路由
app.include_router(auth.router)
app.include_router(test.router)
app.include_router(log.router)
app.include_router(users.router)

@app.get("/")
async def root():
    return {"message": "Welcome to FastAPI MySQL Demo"}